<template>
  <!-- // 地图 -->
  <div class="homePageCards1">
    <div class="tcbtn" style="display: flex;flex-wrap: wrap;">
      <div v-for="(tceng, index) of tucengs" :key="index"
        :style="{ 'pointer-events': tucengvalues[index] ? 'none' : '' }">
        <el-checkbox :label="tceng.value" v-model="tucengvalues[index]" @change="bigTucChange(index)">{{
          tceng.text }}</el-checkbox>
      </div>
    </div>
    <div v-if="mapType === 'sb'" class="sctcbtn">
      <el-checkbox-group v-model="classid" @change="handleCheckedDzChange">
        <el-checkbox v-for="item in classidList" :label="item.value" :key="item.value">{{ item.name }}</el-checkbox>
      </el-checkbox-group>
    </div>
    <div v-if="mapType === 'sb'" class="dydjtcbtn">
      <el-checkbox-group v-model="voltage" @change="handleCheckedLineChange">
        <el-checkbox v-for="item in voltageList" :label="item.value" :key="item.value">{{ item.name }}</el-checkbox>
      </el-checkbox-group>
    </div>
    <div v-if="mapType === 'qx'" class="qxtcbtn" style="display: flex;flex-wrap: wrap;align-content: flex-start;">
      <div v-for="(item, i) of qxtypes" :key="i" :style="{ 'pointer-events': qxtyids[i] ? 'none' : '' }">
        <el-checkbox :label="item.value" @change="handleqxtypeChange(i)" v-model="qxtyids[i]">{{
          item.name }}</el-checkbox>
      </div>
    </div>
    <div class="full-box" @click="goBack">
      <img :src="imgUrl2" alt="" />
      <span>返回</span>
    </div>
    <div id="warrmapcomponents" style="width: 100%; height: 100%"></div>
    <canvas id="temperature" style="display:none"></canvas>
    <div id='layercards'></div>
    <div class="bottomLegend" v-if="mapType === 'qx'">
      <Legend :weatherType="weatherType" v-if="weatherType !== 'leibao'" />
    </div>
    <el-dialog title="站内图查看" :visible.sync="showDzZnt" width="50%">
      <div id="zntcontainer" style="width:100%;height:600px" v-if="showDzZnt">zntcontainer</div>
    </el-dialog>
  </div>
</template>
<script>
import WeatherMap from "./mapConfig/map";
import mixins from "./mixins";
// import colorLines from "./mapConfig/config/colorLines";
import Legend from "./Legend.vue";
export default {
  name: "MapComponents",
  mixins: [mixins],
  components: { Legend },
  props: {
    mapId: {
      type: String,
      default: "sy"
    },
    layerCard: {
      type: Boolean,
      default: true
    },
    cityName: {
      type: String,
      default: ""
    },
    mapCenter: {
      type: Array,
      default: () => [111.36730140947924, 31.174022147218216]
    },
    mapZoom: {
      type: Number,
      default: 6.8
    }
  },
  created() {
    if (this.mapId === "yjsy") {
      this.tucengs.splice(4, 1);
    } else if (this.mapId === "mldsy") {
      this.tucengs.splice(3, 1);
    }
  },
  data() {
    return {
      isqpzsdt: false,
      weatherType: "",
      checkedTucs: ["1"],
      map: null, // 基础地图
      weathermap: null,
      imgUrl2: require("../../../assets/img/nofull.png"),
      tucengs: [
        { value: "1", text: "设备" },
        { value: "2", text: "气象" },
        { value: "3", text: "资源" },
        { value: "4", text: "预警" },
        { value: "5", text: "响应" },
        { value: "6", text: "视频" },
        { value: "7", text: "任务" },
        { value: "8", text: "轨迹" }
      ],
      showDzZnt: false,
      movePointMarker: null,
      lineCheckAll: true,
      isZkSelect: false,
      dzCheckAll: true,
      FullScreen: false,
      isFullscreen: false,
      classid: [296, 110, 200, 300, 335, 342, 521, 1300],
      voltage: [1000000, 500000, -800000, 220000, 110000, 35000],
      classidList: [
        {
          name: "发电站",
          devType: "xnfjd",
          value: 296
        },
        {
          name: "变电站",
          devType: "zf01",
          value: 110
        },
        {
          name: "输电线路",
          devType: "xl",
          value: 200
        },
        {
          name: "直流线路",
          devType: "zlxl",
          value: 1300
        },
        {
          name: "馈线",
          devType: "dkx",
          value: 300
        },
        {
          name: "配电台变",
          devType: "0110",
          value: 335
        },
        {
          name: "柱上开关",
          devType: "0113",
          value: 342
        },
        {
          name: "低压落火点",
          devType: "3112",
          value: 521
        }
      ],
      voltageList: [
        {
          name: "1000kV",
          value: 1000000
        },
        {
          name: "800kV",
          value: -800000
        },
        {
          name: "500kV",
          value: 500000
        },
        {
          name: "220kV",
          value: 220000
        },
        {
          name: "110kV",
          value: 110000
        },
        {
          name: "35kV",
          value: 35000
        }
      ]
    };
  },
  beforeDestroy() {
    this.map && this.map.remove();
    this.map = null;
    this.$eventBus.$off("createlayer");
  },
  mounted() {
    this.initGisMaps();
  },
  watch: {
    // 100000线路，300000电站
    classid: {
      handler(val) {
        this.queryRender({
          classid: val,
          voltage: this.voltage,
          visiable: true,
          mode: "all"
        });
      },
      deep: true
    },
    voltage: {
      handler(val) {
        this.queryRender({
          classid: this.classid,
          voltage: val,
          visiable: true,
          mode: "all"
        });
      },
      deep: true
    }
  },
  methods: {
    bigTucChange(key) {
      this.tucengvalues.forEach((el, index) => {
        if (index !== key) {
          this.tucengvalues[index] = false;
        }
      });
      const types = ["sb", "qx", "zy", "yj", "xy", "sp", "rw", "gj"];
      const fns = ["initGisMaps", "createMap", "initSourceMaps", "initYjMaps", "initYjMaps"];
      if (this.mapId === "yjsy") {
        types.splice(4, 1);
        fns.splice(4, 1);
      } else if (this.mapId === "mldsy") {
        types.splice(3, 1);
        fns.splice(3, 1);
      }
      this.mapType = types[key];
      this.clearMarker();
      this.map && this.map.remove();
      this.map = null;
      this.$nextTick(() => {
        this[fns[key]](this.mapType);
      });
    },
    getYjtzdCity(effectRange) {
      const arr = effectRange.split("、").filter(el => el.includes("县") || el.includes("市") || el.includes("区"));
      const newEffList = [];
      arr.forEach(el => {
        if (el.startsWith("湖北省") && (!el.endsWith("省"))) {
          newEffList.push(el.split("省")[1]);
        } else {
          newEffList.push(el);
        }
      });
      const list = [];
      newEffList.forEach(el => {
        if (el.endsWith("县") || el.endsWith("区")) {
          if (el.includes("市")) {
            list.push(el.split("市")[1]);
          } else {
            list.push(el);
          }
        } else if (el.endsWith("市")) {
          if (el.includes("自治州")) {
            list.push(el.split("自治州")[1]);
          } else {
            const index1 = el.indexOf("市");
            const index2 = el.lastIndexOf("市");
            if (index1 === index2) {
              list.push(el);
            } else {
              list.push(el.slice(index1 + 1));
            }
          }
        }
      });
      const newList = [...new Set(list)];
      return newList[0];
    },
    createMap() {
      try {
        const weathermap = new WeatherMap();
        weathermap.init().then(res => {
          this.map = res;
          this.map.on("styledata", () => {
            const style = this.map.getStyle();
            style.glyphs = "aegis://fonts/aegis/{fontstack}/{range}.pbf";
            this.map.setStyle(style, {
              diff: true
            });
          });
          this.map.on("load", () => {
            weathermap.addBound().then(res => {
              window.weathermap = this.weathermap = weathermap;
              this.weatherType = "temperature";
              this.temperatureScene();
              this.createMaker();
            });
          });
        });
      } catch (error) {
        console.log(error);
      }
    },
    async temperatureScene(day, daytime) {
      this.weatherType = "temperature";
      this.getGridData("temperature");
      // const data = require("./mapConfig/result").default.data;
    },
    goBack() {
      this.$emit("closeMap");
    },
    // 根据环境显示不同的地图组件
    initGisMaps() {
      if (process.env.NODE_ENV === "production") {
        this.initPlugin();
      } else {
        this.initYjMaps("sb");
      }
    },
    // 加载插件
    /* global NARIMap */
    /* global Require */
    initPlugin() {
      Require(["PSRMap", "Tools", "SpatialAnalyst"], () => {
        if (NARIMap.Config.examples.notlogin) {
          this.initMap(NARIMap.Config.styles.base);
        } else {
          // 电网GIS地图服务登录
          NARIMap.SGAuth.login()
            .then((result) => {
              if (result.success) {
                console.log("登录成功");
              } else {
                console.log("登录失败", result);
              }
              // 默认打开电网GIS基础地图
              this.initMap(NARIMap.Config.styles.sjBase);
            })
            .catch((err) => {
              console.log("错误", err);
            });
        }
      });
    },
    // 初始化地图
    initMap(styleurl) {
      this.map = new NARIMap.Map({
        container: "warrmapcomponents",
        style: styleurl,
        zoom: this.mapZoom,
        center: this.mapCenter,
        localIdeographFontFamily: "Microsoft YoHei"
      });

      this.map.on("load", () => {
        this.initLayer();
        // this.createMaskBorder();
        // window.map = this.map;
        // 添加电网图层
        this.psrmap = new NARIMap.PSRMap(this.map);
        this.psrmap.addPSR();
        this.psrmap.filter({
          classid: this.classid,
          voltage: this.voltage,
          visiable: true,
          mode: "all"
        });
        this.psrmap.on("click", (features) => {
          if (this.movePointMarker) {
            this.movePointMarker.remove();
            this.movePointMarker = null;
          }
          console.log(features);
          const item = features[0];
          if (item) {
            // 获取更多详情
            const fun = new NARIMap.ResourceQuery.DeviceQuery();
            const devIds = [{
              devId: item.devId,
              devType: item.devType,
              provinceId: item.provinceId,
              distribution: Number(item.distribution)
            }];
            const options = { devIds };
            const sus = res => {
              const details = res.response.result.psrDataList[0].psrList[0];
              const devName = this.classidList.find(sub => sub.devType === item.devType)?.name;
              // const vlevelLE = this.voltageList.find(sub => sub.value == item.vlevelLE)?.name;
              const str = `<div style="padding: 15px 6px;background: #fff;color: #333;position: relative;">
                                    <div style="padding: 3px;font-size: 18px;font-weight: 600;">台账信息：</div>
                                    <div style="padding: 4px;font-size: 16px;">设备类型：${devName || ""}</div>
                                    <div style="padding: 4px;font-size: 16px;">设备名称：${item.devName}</div>
                                    <div style="padding: 4px;font-size: 16px;">电压等级：${details.vlevelName}</div>
                                    <div style="padding: 4px;font-size: 16px;">运维单位：${details.maintOrgName}</div>
                                    <div style="padding: 4px;font-size: 16px;">维护班组：${details.maintCrewName}</div>
                                    ${details.psrType === "zf01" ? '<div id="zntBtn" style="padding: 3px;">查看站内图</div>' : "<div></div>"}
                                </div>`;
              const el = document.createElement("div");
              el.innerHTML = str;
              el.className = "marker";
              this.movePointMarker = new NARIMap.Marker(el);
              this.movePointMarker.setLngLat(item.attributes.lnglat).addTo(this.map);
              el.onclick = (e) => {
                e.stopPropagation();
                if (e.target.id === "zntBtn") {
                  this.showDzZnt = true;
                  this.$nextTick(() => {
                    this.initZnMap(details);
                  });
                } else {
                  this.movePointMarker.remove();
                }
              };
            };
            const fail = fail => {
              console.log(fail);
            };
            fun.queryDeviceByIds(options, sus, fail);
          }
        });
        if (this.layerCard) {
          this.initLayerCard();
        }
        if (this.cityName) {
          SGMap.plugin(["SGMap.DistrictTask"]).then(() => {
            this.search(this.cityName);
          });
        }
        this.$eventBus.$on("createlayer", (name) => {
          console.log("定位城市", name);
          SGMap.plugin(["SGMap.DistrictTask"]).then(() => {
            this.search(name);
          });
        });
      });
    },
    handleCheckedDzChange(val) {
      this.dzCheckAll = this.classidList.length === val.length;
    },
    handleCheckedLineChange(val) {
      this.lineCheckAll = this.voltageList.length === val.length;
    },
    /* global LayerCards */
    initLayerCard() {
      SGMap.plugin(["SGMap.RoadNetLayer"]).then(() => {
        window.l = new LayerCards({
          map: this.map.pmap,
          container: "layercards"
        });
      });
    },
    // 根据筛选条件过滤
    queryRender(options) {
      this.psrmap && this.psrmap.filter(options);
    },
    // 全选
    stationChange(val) {
      this.classid = val ? this.classidList.map(i => i.value) : [];
    },
    lineChange(val) {
      this.voltage = val ? this.voltageList.map(i => i.value) : [];
    },
    initLayer() {
      this.map.addLayer({
        id: "province-polygon",
        type: "fill",
        source: {
          type: "geojson",
          data: {
            type: "FeatureCollection",
            features: []
          }
        },
        paint: {
          "fill-color": "#206bf5",
          "fill-opacity": 0.3
        }
      });
      this.map.addLayer({
        id: "province-line",
        type: "line",
        source: {
          type: "geojson",
          data: {
            type: "FeatureCollection",
            features: []
          }
        },
        layout: {
          "line-cap": "round",
          "line-join": "round"
        },
        paint: {
          "line-color": "#3995ea",
          "line-width": 2
        }
      });
    },
    // 创建站内图
    initZnMap(details) {
      console.log(details);
      const stationmap = new NARIMap.StationMap();
      // 总部、省侧psrType不同，需要动态获取
      // const devType = NARIMap.PsrTypeMapper.classIdToPsrTypes([110])[0];
      stationmap.init({
        // 地图绑定的DOM元素ID
        container: "zntcontainer",
        station: {
          devid: details.psrId, // 设备id
          classid: 110, // 图层类型
          vlogate: Number(details.vlevelCode), // 电压等级
          deviceType: details.psrType, // 国网设备类型
          distribution: 1, // 主配网标志
          provinceId: details.provinceId// 分省ID
        },
        fullExtent: NARIMap.Config.examples.fullExtent,
        isLoadAnno: false,
        onload: () => {
          // 添加设备点击事件
          // stationmap.getPsrMap().on("click", (features) => {
          //   console.log(features);
          // });
        }
      });
    },
    search(name) {
      const districtTask = new SGMap.DistrictTask();
      districtTask
        .searchDistrict({
          keyword: name,
          extension: true,
          subdistrict: "1"
        })
        .then((result) => {
          if (!result.data) return;
          result = result.data;
          if (!result.districts) {
            return;
          }
          var provinceFeatures = [];
          for (var i = 0; i < result.districts.length; i++) {
            provinceFeatures.push({
              type: "Feature",
              geometry: result.districts[i].shape
            });
          }
          // 更新图层数据
          this.map.getSource("province-polygon").setData({
            type: "FeatureCollection",
            features: provinceFeatures
          });
          this.map.getSource("province-line").setData({
            type: "FeatureCollection",
            features: provinceFeatures
          });
          this.map.flyTo({
            center: result.districts[0].center.split(","),
            zoom: 8
          });
        });
    }
  }
};
</script>

<style scoped lang="less">
:deep(.popupBg) {
  width: 30px;
  height: 30px;
  margin-right: 10px;
  background-image: url("../../../assets/img/ckDetail.png");
  background-repeat: no-repeat;
}

.homePageCards1 {
  position: relative;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  // padding: 6px;
  border-radius: 5px;

  #map {
    border-radius: 5px;
  }

  :deep(.el-dialog__body) {
    padding: 0;
  }

  :deep(.el-dialog__header) {
    background: #5077ff;

    .el-dialog__title {
      color: #fff;
    }

    .el-dialog__headerbtn {
      top: 5px;
      font-size: 30px !important;
    }

    .el-icon-close {
      color: #fff;
    }

    padding: 10px;
  }
}

:deep(.epgis-popup) {
  max-width: 600px !important;
}

.filterbtn {
  position: absolute;
  width: 32px;
  height: 32px;
  left: 10px;
  top: 46px;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 10;
}

.tcbtn {
  position: absolute;
  left: 10px;
  top: 10px;
  z-index: 10;
  display: flex;
  width: 360px;
  height: 200px;
  background: linear-gradient(to right, #264F86, #264F8680);
  padding: 10px;
}

.sctcbtn,
.qxtcbtn {
  position: absolute;
  left: 10px;
  top: 240px;
  z-index: 10;
  display: flex;
  width: 360px;
  height: 200px;
  background: linear-gradient(to right, #264F86, #264F8680);
  padding: 10px;
}

.dydjtcbtn {
  position: absolute;
  left: 10px;
  top: 470px;
  z-index: 10;
  display: flex;
  width: 360px;
  height: 140px;
  background: linear-gradient(to right, #264F86, #264F8680);
  padding: 10px;
}

.full-box {
  position: absolute;
  top: 10px;
  right: 10px;
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 700;
  z-index: 9;
  background-color: #fff;
  cursor: pointer;
  padding: 3px 8px;
  border-radius: 5px;

  img {
    width: 15px;
    height: 15px;
    margin-right: 5px;
  }
}

.tcbtn,
.qxtcbtn {
  :deep(.el-checkbox__inner) {
    width: 26px;
    height: 26px;
    background: #ccc;
  }

  :deep(.el-checkbox__inner::after) {
    left: 9px;
    top: 1px;
    width: 8px;
    height: 15px;
  }

  /deep/.el-checkbox {
    color: #fff;
    display: flex;
    width: 180px;
    align-items: center;
  }
}

.sctcbtn,
.dydjtcbtn {
  /deep/ .el-checkbox-group {
    display: flex;
    flex-wrap: wrap;
    align-content: flex-start;

    .el-checkbox {
      color: #fff;
      display: flex;
      width: 140px;
      align-items: center;
    }
  }
}

:deep(.el-checkbox__label) {
  font-size: 28px;
  line-height: 48px;
}

:deep(.el-checkbox__inner) {
  width: 26px;
  height: 26px;
  background: #ccc;
}

:deep(.el-checkbox__inner::after) {
  left: 9px;
  top: 1px;
  width: 8px;
  height: 15px;
}

.city-box {
  color: #fff;
  font-weight: bold;
  font-size: 16px;
  text-align: center;
}

.bottomLegend {
  position: absolute;
  bottom: 20px;
  right: 20px;
}

/deep/.sgmap-popup-content {
  background: transparent,
}
</style>
